<template>
  <div id="dxf-container">
    <div id="dxf-canvas"></div>
  </div>
</template>

<script>
  import * as THREE from 'three'
  import OrbitControls from 'threejs-orbit-controls'
  import DxfParser from 'dxf-parser'

  export default {
    name: "DXF3D",
    data() {
      return {
        dxf3D: null,
        group: null

      }
    },
    methods: {
      loadDxf(url, index) {
        const _this = this
        var loader = new THREE.FileLoader();
        loader.load(
          url,
          // onLoad回调
          function (data) {
            var parser = new DxfParser();
            try {
              var dxf = parser.parseSync(data);
              console.log(dxf)
              let mesh = _this.createEntities(dxf.entities, index)

              _this.group.add(mesh)
            } catch (err) {
              return console.error(err.stack);
            }
          },
          // onProgress回调
          function (xhr) {
            console.log((xhr.loaded / xhr.total * 100) + '% loaded');
          },
          // onError回调
          function (err) {
            console.error('An error happened');
          }
        );
      },
      createEntities(entities, index) {
        if (entities === undefined || entities.length === 0) {
          return
        }
        const len = entities.length
        let faces = []
        for (let i = 0; i < len; i++) {
          if (entities[i].type === '3DFACE') {
            faces.push(entities[i])
          }
        }
        let vPoints = []
        let face3ds = []
        for (let i = 0; i < faces.length; i++) {
          faces[i].vertices.slice(0, 4).forEach(v => {
            vPoints.push(new THREE.Vector3(v.x, v.y, v.z))
          })
          var color = new THREE.Color(faces[i].color)
          face3ds.push(new THREE.Face3(0 + i * 4, 3 + i * 4, 2 + i * 4, new THREE.Vector3(), color), new THREE.Face3(2 + i * 4, 0 + i * 4, 1 + i * 4, new THREE.Vector3(), color))

        }
        var geometry = new THREE.Geometry();
        geometry.vertices = vPoints
        geometry.faces = face3ds
        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
        var material1 = new THREE.MeshStandardMaterial({vertexColors: THREE.FaceColors,flatShading:true});
       // var material2 = new THREE.MeshNormalMaterial({flatShading:true});
        let mesh = new THREE.Mesh(geometry, [material1]);
        if (index === 1) {
          mesh.position.setY(0.35)
        }
        if (index === 2) {
          mesh.position.setY(0.68)
          mesh.position.setZ(0.3)
        }
        if (index === 3) {
          mesh.position.setY(1.35)
          mesh.position.setZ(0.3)
          mesh.rotateX(Math.PI/2+Math.PI/16)
        }
        if(index === 4){
          mesh.rotateX(Math.PI/2+Math.PI/16)
          mesh.position.setY(1.42)
          mesh.position.setZ(0.71)
        }
        if(index === 5){
          mesh.position.setY(1.42)
          mesh.position.setZ(0.9)
        }
        if(index === 6){
          mesh.position.set(1,1,0)
        }
        return mesh
      },

      ccw(a, b, c) {
        let m00 = a.x;
        let m01 = a.y;
        let m02 = a.z;

        let m10 = b.x;
        let m11 = b.y;
        let m12 = b.z;

        let m20 = c.x;
        let m21 = c.y;
        let m22 = c.z;

        // 计算det.
        let f =
          m00 * (m11 * m22 - m12 * m21)
          + m01 * (m12 * m20 - m10 * m22)
          + m02 * (m10 * m21 - m11 * m20);
        //返回1表示顺时针，0表示三点共线，-1表示逆时针
        return f > 0 ? 1 : f < 0 ? -1 : 0;
      }
    },
    mounted() {
      let scene = new THREE.Scene();
      scene.background = new THREE.Color(0xf0f0f0)
      var axes = new THREE.AxesHelper(100)
      scene.add(axes)
      var camera = new THREE.PerspectiveCamera(1.5, window.innerWidth / window.innerHeight, 0.1, 10000);
      var controls = new OrbitControls(camera, document.getElementById('dxf-canvas'));
      //  var camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 1000 );
      var raycaster = new THREE.Raycaster();
      var mouse = new THREE.Vector2();

      var renderer = new THREE.WebGLRenderer({antialias:true});


      renderer.setSize(4 * window.innerWidth / 5, window.innerHeight);
      document.getElementById('dxf-canvas').appendChild(renderer.domElement)
      this.group = new THREE.Group()

      scene.add(this.group)

     var ambientLight = new THREE.AmbientLight( 0xcccccc);
      scene.add( ambientLight );

      var pointLight = new THREE.PointLight( 0xcccccc);
      pointLight.position.set( 20, 10, 150 );
      scene.add( pointLight );
     var  hemisphereLight=new THREE.HemisphereLight(0xffffbb, 0x080820, 1)
      scene.add( hemisphereLight )
      camera.position.set(20, 10, 150);
      controls.update();


      var animate = function () {
        requestAnimationFrame(animate);
        controls.update();
        renderer.render(scene, camera);
      };

      function onMouseMove(event) {
        event.preventDefault();
        mouse.x = ((event.clientX - renderer.domElement.getBoundingClientRect().left) / renderer.domElement.offsetWidth) * 2 - 1;
        mouse.y = -((event.clientY - renderer.domElement.getBoundingClientRect().top) / renderer.domElement.offsetHeight) * 2 + 1;

        raycaster.setFromCamera(mouse, camera);

        // 计算物体和射线的焦点
        let intersects = raycaster.intersectObjects(scene.children,true);
        for (var i = 0; i < intersects.length; i++) {
          intersects[i].object.material.color.set(0x6699ff);
        }
      }

      requestAnimationFrame(animate)
      window.addEventListener('click', onMouseMove, false);
      this.loadDxf('/robot/b0.dxf', 0)
      this.loadDxf('/robot/b1.dxf', 1)
      this.loadDxf('/robot/b2.dxf',2)
      this.loadDxf('/robot/b3.dxf',3)
      this.loadDxf('/robot/b4.dxf',4)
      this.loadDxf('/robot/b5.dxf',5)
      this.loadDxf('/robot/b6.dxf',6)
  //    this.group.scale.x = 30
  //    this.group.scale.y = 30
  //    this.group.scale.z = 30


    }
  }
</script>

<style scoped>
  .el-form-item__content {
    display: flex;
  }

  input {
    width: 20px;
  }
</style>
